require('dotenv').config();
const axios = require('axios');

const InstrumentId = process.env.InstrumentId;
const START_TIME = process.env.START_TIME;
const END_TIME = process.env.END_TIME;
const JSESSIONID = process.env.JSESSIONID;

function formatMesBulle() {
    const date = new Date();
    const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', timeZoneName: 'short', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
    const formattedDate = date.toLocaleDateString('en-US', options).replace(',', '').replace(/:/g, '%3A').replace(/ /g, '%20');
    return `mesBulle=${encodeURIComponent(formattedDate)}`;
}

const url = 'https://s.ilab.cn/yq/addConverntion';
const data = `instrumentId=${InstrumentId}&stime=${START_TIME}&etime=${END_TIME}&remark=&phone=19993443939`;
const headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
    'Cookie': `addInstr=addInstr; yq_show_type=liebiao; ${formatMesBulle()}; Hm_lvt_3f8979c5a4c7963ca4968f378e5a431a=1714146361; Hm_lpvt_3f8979c5a4c7963ca4968f378e5a431a=1714146361; JSESSIONID=${JSESSIONID};ilab_uname=19993443939`,
    'Origin': 'https://s.ilab.cn',
    'Referer': 'https://s.ilab.cn/yq/initConvention?instrumentId=385c09c117e34be09e2ffc04bb244fa5',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
};

function sendRequest() {
    axios.post(url, data, { headers })
        .then(response => {
            console.log('Status:', response.status);
            console.log('Data:', response.data);
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

const now = new Date();
let startTime, endTime;

if (now.getHours() === 0) {
    startTime = new Date(now);
    startTime.setDate(now.getDate() - 1);
    startTime.setHours(23, 59, 59, 400);
} else {
    startTime = new Date(now);
    startTime.setHours(23, 59, 59, 400);
}

endTime = new Date(startTime.getTime() + 6005);

if (now < endTime) {
    setTimeout(() => {
        const interval = setInterval(() => {
            if (new Date() > endTime) {
                clearInterval(interval);
                console.log('Finished sending requests.');
            } else {
                sendRequest();
            }
        }, 100);
    }, startTime - now);
} else {
    console.log('end time is in the past. Please adjust the end time.');
}
